package web.controller;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <b>URIParser  </b>
 * <p>URIParser classe pour parser une url et lui rajouter ou enlever des paramètres.</p>
 * 
 */
public class URIParser {

	private URL url;
	private String urlQuery;
	private Map<String, String> query;
	
	/**
     * analyse une url et determine les paramètres
     */
	public URIParser(String url) throws MalformedURLException {
		
		try {
			this.url = new URL(url);
		} catch (MalformedURLException e) {
			this.url = new URL("http://localhost:8080/ASOF/"+url);
		}
		this.urlQuery = this.url.getQuery();
		this.query = new HashMap<String, String>();
		if(this.urlQuery != null){
			this.query = getQueryMap(this.urlQuery);
		}
	}

	/**
     * reconstruit l'url
     */
	public String getUrl() {
		String url = getPath();	

		//parameters
		if(!this.query.isEmpty()){

			url +="?";
			int j = 0;
			Set<String> keys = this.query.keySet();
			for (String key : keys){
				if(j != 0)
					url +="&";
				url += key+"="+this.query.get(key);
				j++;
			}
			
		}
		return (url);
	}
	
	public String getPath(){
		String [] paths = this.url.getPath().split("/");
		String path = "";
		int j = 2;
		
		for (int i=2;i<paths.length;i++){
			if(j != 2)
				path +="/";
			path += paths [i];
			j++;
		}
		return path;
	}
	
	/**
     * renvoi la list des paramètres
     */
	private Map<String, String> getQueryMap(String query){ 
		
	    String[] params = query.split("&");  
	    Map<String, String> map = new HashMap<String, String>();  
	    for (String param : params)  
	    {  
	        String name = param.split("=")[0];  
	        String value = param.split("=")[1];  
	        map.put(name, value);  
	    }  
	    return map;  
	}
	
	/**
     * renvoi la valeur d'un paramètre
     */
	public String getParameter (String param){
			
		if (this.query.containsKey(param)){  
		      return this.query.get(param);
		}else{
			return null;
		}
	}
	
	/**
     * modifie ou rajouter un paramètre
     */
	public void setParameter (String param, String value){
		
		this.query.put(param, value);
	}
	
	public void removeParameter (String param){
		
		if(this.query.containsKey(param))
			this.query.remove(param);
	}
}
